package chu.dejian.ui.fragmet;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import com.sam.map.NoUIGetLocation;
import com.sam.ui.base.fragment.BaseFragment;
import com.sam.utils.L;
import com.sam.utils.NetUtil;
import com.sam.utils.T;

import java.util.ArrayList;
import java.util.List;

import chu.dejian.db.DBHelper;
import chu.dejian.entity.RecordEntity;
import chu.dejian.models.PostMeasurementRequest;
import chu.dejian.restApi.RestClient;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MeasureResultFragment extends BaseFragment {
    private static MeasureResultFragment instance;
    private static double latitude, longitude;

    public synchronized static MeasureResultFragment getInstance() {
        if (instance == null) {
            instance = new MeasureResultFragment();
        }
        return instance;
    }

    private TextView shrinkageValueTV, diastolicValueTV, pulseValueTV, arrhythmiaTV;
    private View measureAgainBtn, seekAdviceBtn;
    private RecordEntity recordEntity;
    private View referenceBtn;
    private TextView debugTV;
    ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_measure_result);
    }

    @Override
    public void findView() {
        shrinkageValueTV = (TextView) findViewById(R.id.shrinkage_value);
        diastolicValueTV = (TextView) findViewById(R.id.diastolic_value);
        pulseValueTV = (TextView) findViewById(R.id.pulse_value);
        arrhythmiaTV = (TextView) findViewById(R.id.arrhythmia_value);

        measureAgainBtn = findViewById(R.id.measure_again);
        referenceBtn = findViewById(R.id.reference_table);
        seekAdviceBtn = findViewById(R.id.seek_medical_advice);
        debugTV = (TextView) findViewById(R.id.result_data);
    }

    @Override
    public void initView() {
        measureAgainBtn.setOnClickListener(onClickListener);
        referenceBtn.setOnClickListener(onClickListener);
        seekAdviceBtn.setOnClickListener(onClickListener);
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle bundle = getArgumentBundle();
        RecordEntity newRecord = bundle.getParcelable("record");
        if (newRecord != null) {
            if(newRecord != recordEntity) DBHelper.getInstance().getRecordDao().insertRecord(newRecord);   // 直接存储吧
            recordEntity = newRecord;
            shrinkageValueTV.setText(recordEntity.systolic + "");
            diastolicValueTV.setText(recordEntity.diastolic + "");
            pulseValueTV.setText(recordEntity.pulse + "");
            arrhythmiaTV.setText(recordEntity.pulseState == 1 ? R.string.arrhythmia : R.string.normal);
//			if(NetUtil.checkNetWork(getActivity())) uploadMeasurement(recordEntity);
        }
        uploadAllRecords();
		/*String resultData = bundle.getString("data");
        if(resultData == null) debugTV.setVisibility(View.GONE);
		else {
			debugTV.setVisibility(View.VISIBLE);
			debugTV.setText(resultData);
		}*/

    }

    public void uploadAllRecords() {
        L.d("尝试同步记录到云端");
        if (!NetUtil.checkNetWork(getActivity())) return;
        if (latitude > 0 && longitude > 0) {
            new UploadRecordThread().start();
            return;
        }
        // 还没有获取位置，那就先获取位置再上传
        NoUIGetLocation.getInstance(getActivity()).startLocate(new NoUIGetLocation.OnLocationInfoReturnListener() {
            @Override
            public void onLocationInfoReturn(BDLocation location, double latitude, double longitude, String address) {
                if (latitude > 0 && longitude > 0) {
                    MeasureResultFragment.latitude = latitude;
                    MeasureResultFragment.longitude = longitude;
                    NoUIGetLocation.getInstance(getActivity()).stopLocate();
                    new UploadRecordThread().start();
                }
            }
        });
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int i = v.getId();
            if (i == R.id.measure_again) {
                replaceSelfWithFragment(MeasureFragment.getInstance());

            } else if (i == R.id.reference_table) {
                replaceSelfWithFragment(ReferenceTableFragment.getInstance());
            } else if (i == R.id.seek_medical_advice) {
                BLEBRHelper.getInstance().sendSeekAdviceBR(getActivity());
            }
        }
    };

    List<RecordEntity> recordEntities = new ArrayList<>();
    class UploadRecordThread extends Thread {
        private boolean isRunning = false;

        @Override
        public synchronized void start() {
//            if (isRunning) return;
            super.start();
//            isRunning = true;
        }

        @Override
        public synchronized void run() {
            L.d("开始同步记录到云端");
            synchronized (recordEntities){
                List<RecordEntity> records = DBHelper.getInstance().getRecordDao().getAllUnuploadedRecord();
                if (records == null || records.size() == 0) return;
                records.removeAll(recordEntities);
                recordEntities.addAll(records);
                for (RecordEntity recordEntity : records) {
                    uploadMeasurement(recordEntity);
                }
            }
//            isRunning = false;
        }
    }

    private int retryTimes = 0;
    private static final long INTERVAL_RETRY_MILLIS = 5000;
    private static final int RETRY_TIMES = 10;

    public void uploadMeasurement(final RecordEntity recordEntity) {
        retryTimes++;
        RestClient.getAuthedClient().getApiService().postMeasurement(new PostMeasurementRequest(recordEntity, latitude, longitude), new Callback() {
            @Override
            public void success(Object o, Response response) {
                if (response.getStatus() == 401) {
                    BLEBRHelper.getInstance().sendReloginBR(getActivity());
                    T.showShort(getActivity(), R.string.nauthorized_and_relogin);
                    return;
                }
                if (response.getStatus() == 201) {
                    L.e(recordEntity.toString()+"上传记录成功");
                    retryTimes = 0;
                    DBHelper.getInstance().getRecordDao().setRecordUploaded(recordEntity.recordId);
                    getArgumentBundle().clear(); // 清除下参数
                } else if (retryTimes < RETRY_TIMES) {
                    L.e("上传记录失败");
                    try {
                        Thread.sleep(INTERVAL_RETRY_MILLIS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    uploadMeasurement(recordEntity);  // 递归上传
                    retryTimes = 0;
                }
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                L.e("上传记录失败");
                if (retryTimes < RETRY_TIMES) {
                    try {
                        Thread.sleep(INTERVAL_RETRY_MILLIS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    uploadMeasurement(recordEntity);  // 递归上传
                    retryTimes = 0;
                }
            }
        });
    }
}
